package com.github.m6d21.sso.support.proxy;

import static org.slf4j.LoggerFactory.getLogger;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.slf4j.Logger;

public abstract class AbstractCglibInterceptorHandler implements MethodInterceptor {

    private static final Logger LOGGER = getLogger(AbstractCglibInterceptorHandler.class);

    @SuppressWarnings({"all"})
    public final <T> T newInstance(Class<? extends Object> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public final Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) {
        Object result = null;
        try {
            if (!Object.class.equals(method.getDeclaringClass())) {
                beforeInvoke(o, method, objects);
                result = methodProxy.invokeSuper(o, objects);
                afterInvoke(o, method, objects, result);
            }
        } catch (Throwable throwable) {
            handleException(o, method, objects, throwable);
        }
        return result;
    }

    protected abstract void beforeInvoke(Object o, Method method, Object[] args);

    protected abstract void afterInvoke(Object o, Method method, Object[] args, Object result);

    protected abstract void handleException(Object o, Method method, Object[] args, Throwable throwable);
}
